﻿# -*-coding: UTF-8 -*-

class Timer:
	def __init__(self):
		self.timer_id = None
		self.function = None
		self.args = None
		self.kwargs = None
		self.active = True

	def setup(self, timer_id, *args, **kwargs):
		"""设置定时器参数，使用可变参数保持签名一致性"""
		self.timer_id = timer_id
		self.active = True
		return self

	def set_callback(self, function, *args, **kwargs):
		"""设置回调函数和参数"""
		self.function = function
		self.args = args
		self.kwargs = kwargs
		return self

	def reset(self):
		"""重置定时器状态"""
		self.timer_id = None
		self.function = None
		self.args = None
		self.kwargs = None
		self.active = True

	def tick(self, delta_time):
		return True

	def invoke(self):
		if self.active and self.function:
			self.function(*self.args, **self.kwargs)

	def cancel(self):
		self.active = False


class RepeatTimer(Timer):
	def __init__(self):
		super().__init__()
		self.interval = 0
		self.accumulated_time = 0.0

	def setup(self, timer_id, *args, **kwargs):
		"""设置重复定时器的ID和间隔"""
		super().setup(timer_id, *args, **kwargs)
		# 第一个位置参数作为间隔时间
		if args and len(args) > 0:
			self.interval = args[0]
		elif 'interval' in kwargs:
			self.interval = kwargs['interval']
		else:
			self.interval = 0

		self.accumulated_time = 0.0
		return self

	def reset(self):
		super().reset()
		self.interval = 0
		self.accumulated_time = 0.0

	def tick(self, delta_time):
		if not self.active:
			return True

		self.accumulated_time += delta_time
		if self.accumulated_time >= self.interval:
			self.accumulated_time -= self.interval
			self.invoke()

		return False  # 重复定时器永不自动移除


class DelayTimer(Timer):
	def __init__(self):
		super().__init__()
		self.delay = 0
		self.elapsed_time = 0.0

	def setup(self, timer_id, *args, **kwargs):
		"""设置延迟定时器的ID和延迟时间"""
		super().setup(timer_id, *args, **kwargs)
		# 第一个位置参数作为延迟时间
		if args and len(args) > 0:
			self.delay = args[0]
		elif 'delay' in kwargs:
			self.delay = kwargs['delay']
		else:
			self.delay = 0

		self.elapsed_time = 0.0
		return self

	def reset(self):
		super().reset()
		self.delay = 0
		self.elapsed_time = 0.0

	def tick(self, delta_time):
		if not self.active:
			return True

		self.elapsed_time += delta_time
		if self.elapsed_time >= self.delay:
			self.invoke()
			return True  # 延迟定时器执行一次后需要移除

		return False
